/**
 * v-permission指令
 *
 * @example 验证job
 * <button v-permission="'job1'">修改</button>
 * <button v-permission="['job1','job2']">修改</button>
 * <button v-permission="{job:'job1'}">修改</button>
 *
 * @example 验证job, clientOrgClass 和 自定义权限scope
 * <button v-permission="{job:'job1', org:'org1', scope: 'authKey'}">修改</button>
 * <button v-permission="{job:['job1','job2'], org:['org1','org2'], scope: ['authKey1', 'scopeKey2']}">修改</button>
 *
 * @example 验证orgRegionLever
 * <button v-permission="{level:1}">修改</button>
 * <button v-permission="{level:[1,2,3]}">修改</button>
 *
 * @example 排除
 * <button v-permission.exjob.exorg.exlevel.exscope="{job:'job1', org:'org1', level: 3, scope: 'authKey'}">修改</button>
 */

import { isObject } from '@vimi/utils-tool'

const keyStrat = {
  job: 'job',
  org: 'clientOrgClass',
  level: 'orgRegionLever',
  scope: 'scopeArr',
}

function checkValue(rules, userData, isReverse) {
  if (!rules) return !isReverse
  const isUserArr = Array.isArray(userData)
  const valid = Array.isArray(rules)
    ? isUserArr
      ? rules.some(val => userData.includes(val))
      : rules.includes(userData)
    : isUserArr
    ? userData.includes(rules)
    : rules === userData
  return isReverse ? !valid : valid
}

function permissionValidate(value, user, modifiers) {
  if (!isObject(value)) {
    value = { job: value }
  }
  for (const key in value) {
    if (!checkValue(value[key], user[keyStrat[key]], modifiers[`ex${key}`])) {
      return false
    }
  }
  return true
}

export default {
  inserted(el, binding, vnode) {
    const { value, modifiers } = binding
    const { componentInstance: that } = vnode
    if (!value || !that) return

    const user = that.$store.getters.user || {}
    if (!permissionValidate(value, user, modifiers)) {
      el.parentNode && el.parentNode.removeChild(el)
    }
  },
}
